package com.designpatterns.ReadersWriter;

import java.util.concurrent.TimeUnit;

/**
 * Created by 41579 on 2017/6/9.
 */
public class WriteThread implements Runnable {
    private ReadWriteLock readWriteLock;

    public WriteThread(ReadWriteLock readWriteLock) {
        this.readWriteLock = readWriteLock;
    }

    private void doWrite() throws InterruptedException {
        this.log("begin writting", this.readWriteLock);
        TimeUnit.SECONDS.sleep(3);
        this.log("end writting", this.readWriteLock);
    }

    private void log(String str, ReadWriteLock readWriteLock) {
        StringBuilder sb = new StringBuilder();
        sb.append(Thread.currentThread().getName()+"【"+str + "】:");
        sb.append("{readingReaders=" + readWriteLock.getReadingReaders()+"}");
        sb.append("{writtingWriters=" + readWriteLock.getWrittingWriters()+"}");
        sb.append("{waittingWriters=" + readWriteLock.getWaittingWriters()+"}");
        System.out.println(sb.toString());
    }

    @Override
    public void run() {
        try {
            readWriteLock.getWriteLock().lock();
            doWrite();
            readWriteLock.getWriteLock().unlock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
